package org.paradigmshift.timelapse.daos

import net.liftweb.json._
import org.paradigmshift.timelapse.domain.Worklog
import org.paradigmshift.timelapse.rest.JsonRestConnection
import org.paradigmshift.timelapse.serializers.WorklogSerializer

object WorklogDao {
  
  private implicit val formats = DefaultFormats + new WorklogSerializer
  private def toJson( worklog:Worklog ):String = compact( render( Extraction.decompose( worklog ) ) )
  
  def create( issueKey:String, worklog:Worklog ) {
    JsonRestConnection.post( "/issue/" + issueKey + "/worklog", toJson( worklog ) )
  }
  
  def update( issueKey:String, worklog:Worklog ) {
    for { id <- worklog.id; if (id != "") } yield {
      JsonRestConnection.put( "/issue/" + issueKey + "/worklog/" + id, toJson( worklog ) )
    }
  }
  
  def delete( issueKey: String, worklog:Worklog ) {
    for { id <- worklog.id; if (id != "") } yield {
      JsonRestConnection.delete( "/issue/" + issueKey + "/worklog/" + id )
    }
  }
  
  def findByIssueKeyAndId( issueKey:String, worklogId:String ) = {
    val response = JsonRestConnection.get( "/issue/" + issueKey + "/worklog/" + worklogId, Map() )
    for { jsonString <- response } yield {
      val json = parse( jsonString )
      json.extract[Worklog]
    }
  }
  
  def findByIssueKey( issueKey:String ):List[Worklog] = {
    val response = JsonRestConnection.get( "/issue/" + issueKey + "/worklog", Map() )
    (for { jsonString <- response } yield {
      val json = parse( jsonString )
      (json \ "worklogs").children.map( jsonWorklog => jsonWorklog.extract[Worklog] )
    }).getOrElse( Nil )
  }
}